<?php
namespace plugins\appmarket\controller; //Demo插件英文名，改成你的插件英文就行了
use cmf\controller\PluginAdminBaseController;//引入此类
use think\Db;
use think\Cookie;
use plugins\appmarket\model\AdminIndexModel;
use plugins\appmarket\model\ModulePurchaseHistoryModel;
use app\common\lib\AccessAuthorization;
use plugins\appmarket\controller\AuditController;
/**
 * 应用市场控制器
 * 需求配置首页
*@actionInfo(
*  'name' => '应用市场',
*  'symbol' => 'appmarket',
*  'list' => [
*      'get_wechat_pay_code' => [
*          'demandName' => '微信支付模块' ,
*          'demandSymbol' => 'WechatPay',
*          'explain' => '获取微信支付码'
*      ]
*  ]
 *)
 */
class AdminIndexController extends PluginAdminBaseController
{
    /**
     * coolie过期时间 默认2小时 单位：毫秒
     * @var [type]
     */
    protected $cookieExpire =  7200 ;

    protected function _initialize()
    {
        parent::_initialize();
        $adminId = cmf_get_current_admin_id();
        //获取后台管理员id，可判断是否登录
        if (!empty($adminId)) {
            $this->assign("admin_id", $adminId);
        }
    }

    /**
     * @adminMenu(
     *     'name'   => '应用市场',
     *     'parent' => 'admin/Plugin/default',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 1000,
     *     'icon'   => '',
     *     'remark' => '应用市场',
     *     'param'  => ''
     * )
     **/
    public function index()
    {
        $data = $this->request->param();
		
        //搜索参数
        $search = [
            'categoryTmp'   =>      isset( $data [ 'categoryTmp' ] ) ? $data [ 'categoryTmp' ] : '0/全部分类' ,
            'category'      =>      isset( $data [ 'categoryTmp' ] ) ? substr( $data ['categoryTmp'] , 0 , strpos( $data ['categoryTmp'] , '/' ) ) : 0 ,
            'categoryName'  =>      isset( $data [ 'categoryTmp' ] ) ? substr( $data ['categoryTmp'] , strpos( $data ['categoryTmp'] , '/' )+1 ) : '全部分类' ,
            'payment'       =>      isset( $data [ 'payment' ] ) ? $data [ 'payment' ] : 100,
            'buy'           =>      isset( $data [ 'buy' ] ) ? $data [ 'buy' ] : 0,
			'keywords'           =>      isset( $data [ 'keywords' ] ) ? $data [ 'keywords' ] : '',
            'search'        =>      isset( $data [ 'search' ] ) ? $data [ 'search' ] : null
        ]; 
        $adminIndexModel = new AdminIndexModel();
        $field = 'id,name,title,putway,version,introduce,status,describe,price,author,author_id,category';
        $list = $adminIndexModel->appList( cmf_get_current_admin_id(), $field , $search );
		
		$moduleList = $this->getModuleStoreModuleList();
		$this->assign( 'moduleList' , $moduleList );

        $categoryList = Db::name( 'module_category' )->select()->toArray();
        $this->assign( 'search' , $search );
        $this->assign( 'searchObj' , json_encode( $search ) );
        $this->assign( 'categoryList' , $categoryList );
        $this->assign( 'list' , $list );
        $this->assign( 'page' , $list->render() );
        return $this->fetch( 'admin_index/index' );
    }
	//获取应用市场的模块列表
	private function getModuleStoreModuleList()
	{
		$list = Db::name('module_store')->group('title')->column('title');
		return $list;
	}
	 /**
     * @adminMenu(
     *     'name'   => '应用市场首页',
     *     'parent' => 'index',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 990,
     *     'icon'   => '',
     *     'remark' => '应用市场首页',
     *     'param'  => ''
     * )
     **/
	public function appmarketIndex()
	{
		return $this->index();
	}

    /**
     * 查看模块详情页面
     *
     */
    public function particular( $id )
    {
        $module = Db::name( 'module_store' )->where( 'id' , $id )->find();
        $previewList = [];
        if( !empty($module['preview']) ){
            $previewList = explode(',', $module['preview']);
        }
        $this->assign( 'previewList' , $previewList );
        $this->assign( 'module' , $module );
        return $this->fetch();
    }
    
    /**
     * 登录页面
     * @return [type] [description]
     */
    public function login()
    {
       return $this->fetch();
    }

    /**
     * 执行登录
     */
    public function doLogin()
    {
        if( !$this->request->isPost() ){
            //$this->error('请求类型错误，请检查！');
            return zy_json_echo( false , '请求类型错误，请检查！' );
        }
        $data = $this->request->param();
        $name = $data ['name'];
        $pwd = $data['password'];
        $operateType = 1; //1购买操作 2安装操作
        if( empty( $name ) || empty( $pwd ) ){
           // $this->error('账号和密码不能为空！');
           return zy_json_echo( false , '账号和密码不能为空！' );
        }
        //请求主系统验证密码账号
        $userInfo = $this->checkUserInfo( $name ,  $pwd );
        if( false === $userInfo ){
           //$this->error( '登录信息错误，请检查！' );
           return zy_json_echo( false , '登录信息错误，请检查！' );
        }
        $userId = 1;
        $ID = self::userInfoEncode( $userId );
        $UID = self::userInfoEncode( cmf_get_current_admin_id() );
        Cookie::set( 'app_login_info' , [ 'ID' => $ID , 'UID' => $UID ] , $this->cookieExpire );
        return zy_json_echo( true , '登录成功！' );       
    }

    /**
     * 购买
     * @param  $id model_store 模块id
     */
    public function bought()
    {
        $data = $this->request->param();
        $moduleId = $data ['moduleId'];
        //检查是否登录
        $userId = $this->checkLogin();
        if( false === $userId ){
            return zy_json_echo( false , '用户信息错误！' , null , 404 );
        }
        //读取用户信息
        $userInfo = AccessAuthorization::getUserInfo( $userId );

        if( empty( $userInfo ) ){
           return zy_json_echo( false , '用户信息错误！' , null , 404 );
        }

        //检查是否购买
        $isBought = $this->isBought( $moduleId );
        if( $isBought ){
            return zy_json_echo( false , '已购买' , null , 201 );
        }

        if(  $userInfo ['company_id'] == 8 ){
            //免支付购买  购买记录中添加一条数据
            //$this->success('开发者操作，购买成功！');
           //return $this->boughtSuccess('开发者操作，购买成功！');
			$userId = cmf_get_current_admin_id();
            $temp = Db::name( 'user' )->where( [ 'user_type' => 1 , 'user_status' =>1 , 'id' => $userId ] )->find();
            if( empty($temp) ){
				return zy_json_echo(false,'用户信息错误！' , '' ,404);
			}
            self::addBoughtRecord( $userId , $moduleId , 0 ,0 , 0, 1 );
            return zy_json_echo( false , '开发者无需购买产品！' , null , 201  );
        }else{
            return zy_json_echo( true , '进入支付页面' );
        }

    }
    /**
     * 购买成功页面
     */
    public function boughtSuccess( $success = '购买成功！' )
    {
        $this->assign( 'success' , $success );
        return $this->fetch( 'admin_index/success' );
    }

    /**
     * 支付页面
     */
    public function pay( $id )
    {
        //$module = Db::name( 'module_store' )->where( 'id' , $id )->find();
        //$this->assign( 'module' , $module );
        return $this->fetch( 'admin_index/pay' );
    }

    /**
     * 支付确认
     * @return [type] [description]
     */
    public function paySuccess()
    {
        return true;
    }

    /**
     * 检查用户
     * @return [type] [description]
     */
    private function checkUserInfo( $name , $pwd )
    {
        $user = Db::name( 'user' )->where( [ 'user_login' => $name , 'user_pass' => cmf_password($pwd) ] )->find();
        if( empty( $user ) ){
            return false;
        }
        return $user[ 'id' ];
    }


    /**
     * 检查是否登录
     */
    public function checkLogin()
    {
        $appLoginInfo = []; 
        //读取cookie数据  app_login_info = ['ID'=>]
        //ID = base_encode64( mt_rand(100000,999999).$id )  6位随机数 + $userid
        if( Cookie::has( 'app_login_info' ) ){
            $appLoginInfo = Cookie::get( 'app_login_info' );
        }
        if( !isset( $appLoginInfo['ID'] ) || !isset( $appLoginInfo['UID'] ) ){
            return false;
        }
        $userId = self::userInfoDecode( $appLoginInfo['ID'] );
        $UID = self::userInfoDecode( $appLoginInfo['UID'] );
        if( $UID != cmf_get_current_admin_id() ){
            return false;
        }
        return empty( $userId ) ? false : $userId;
    }   

    /**
     * cookie用户信息加密
     */
    private static function userInfoEncode( $userId )
    {
        $rand = mt_rand( 100000 , 999999 );
        return base64_encode( $rand.$userId );
    }
    /**
     * cookie用户信息解密
     */
    private static function userInfoDecode( $ciphertext = '' )
    {
        if( empty( $ciphertext ) ) return '';
        $ciphertext = base64_decode( $ciphertext );
        if( strlen( $ciphertext ) <= 6 ) return '';
        return substr( $ciphertext , 6 );
    }

    /**
     * 登录页面
     * @return [type] [description]
     */
    public function islogin()
    {
       return $this->fetch('admin_index/login');
    }   

    //安装
    //////////////////////////////////////////////////////////////
    /**
     *安装方法
     * @return [type] [description]
     */
    public function installCheck()
    {
        $data = $this->request->param();
        $id = $data['id'];
        //检查是否登录
        $userId = $this->checkLogin();
        if( false === $userId ){
            //跳转登录页面
            return zy_json_echo( false , '请登录' , null , 101 );
        }
        //读取用户信息
        $userInfo = AccessAuthorization::getUserInfo( $userId );

        if( empty( $userInfo ) ){
            //跳转登录页面
            return zy_json_echo( false , '请登录' , null , 101 );
        }
        //检查是否购买
        $moduleId = $id;
        $isBought = $this->isBought( $moduleId );
        if( false === $isBought ){
            return zy_json_echo( false , '还未购买' , null , 102);
        }

        //安装页面
        return zy_json_echo( false , '可以安装' , null , 103);
    }

    /**
     * 是否购买
     * return bool  未购买false 购买true
     */
    public function isBought( $moduleId )
    {
        $companyId = Db::name( 'user_attach' )->where( 'user_id' , cmf_get_current_admin_id() )->value('company_id');
        $where = [
            'company_id' =>  $companyId,
            'module_id'  => $moduleId 
        ];
        $moduleModel = new ModulePurchaseHistoryModel();
        $result = $moduleModel->getPurchaseHistory( $where );
        return empty( $result ) ? false : true ;
    }


    /**
     * 安装页面
     */
    public function install( $moduleId )
    {
        $this->assign( 'moduleId' , $moduleId );
        return $this->fetch('admin_index/install');
    }  
    /**
     * 安装操作
     */
    public function installOperate( $moduleId )
    {
        $module = Db::name( 'module_store' )->where( 'id' , $moduleId )->find();
        //执行安装操作
        $pluginInstallObj = new \app\admin\controller\PluginController();
		$pluginInstallObj->pluginModuleId = $moduleId;
        $res = $pluginInstallObj -> install( $module[ 'name' ] );
        $status = $res [ 'code' ] ? true : false;
        return zy_json_echo( $status , $res [ 'msg' ] ); 
    }

    /**
     *卸载模块操作
     */
    public function unInstallOperate(  )
	{
		
		$data = $this->request->param();
		$name = isset($data [ 'name' ] ) ? $data [ 'name' ] : '';
		$moduleId = Db::name('plugin')->where( 'name' , $name )->value( 'id' );
		if( empty($moduleId) ){
			$this->error('模块不存在,模块标识错误！');
		}
        //执行卸载操作
        $pluginInstallObj = new \app\admin\controller\PluginController();
        $res = $pluginInstallObj -> unInstall( $moduleId );
    }

    /////////////////////////////////////////////////////////////
    /**
     * 添加记录
     */
    private static function addBoughtRecord( $userId , $modulId ,  $expire = 0 ,  $paymentAmount = 0 , $paymentType = 0, $operateType =0 )
    {
        $userName = Db::name( 'user' )->where( 'id' , $userId )->value('user_login');
        $companyId = Db::name( 'user_attach' )->where( 'user_id' , $userId )->value( 'company_id' );
        $data = [
            'company_id' => $companyId,
            'module_id' => $modulId,
            'user_id' => $userId,
            'user_name' => $userName,
            'expire' => $expire,//0永久
            'payment_amount' => $paymentAmount,
            'payment_type' => $paymentType,
            'add_time' => time(),
            'operate_type' => $operateType // 0 用户购买  1 开发者购买 
        ];
        //保存数据
        $moduleModel = new ModulePurchaseHistoryModel();
        $result = $moduleModel->bought( $data );
        return $result;
    }


}